const uwDao = require('../dao/urlWordDao'),
  urlDao = require('../dao/urlDao'),
  wordDao = require('../dao/wordDao'),
  config = require('../util/config'),
  log = require('../util/log'),
  zoroDB = require('../util/zoroDB');
var uws = [],
  processing = false;

exports.add = (uw, fn) => {
  fn = fn || (() => {
  });
  uws.push(uw)
  fn()
}

exports.start = () => {
  if (processing)
    return;
  processing = true;
  var _uws = uws;
  uws = [];
  deal(_uws)
}

function deal(uws) {
  if (uws.length == 0) {
    processing = false;
    return
  }
  const uw = uws[0];
  var p0 = new Promise(resolve => {
      zoroDB.query('select count(*) from url', [], (err, rows, fields) => {
        err && log(err)
        var count = rows[0]['count(*)'],
          learingRate = 1;
        while (count >= 1) {
          count /= 2;
          learingRate /= 2;
        }
        zoroDB.query('update url set p=p*?', [1 - learingRate], (err, result) => {
          err && log(err)
          zoroDB.query('update url set p=p+? where id=?', [learingRate, uw.urlId], (err, result) => {
            err && log(err)
            zoroDB.query('update url set p=? where p<?', [learingRate * learingRate, learingRate * learingRate], (err, result) => {
              err && log(err)
              resolve()
            })
          })
        })
      })
    }),
    p1 = new Promise(resolve => {
      zoroDB.query('select count(*) from url_word where url=?', [uw.urlId], (err, rows, fields) => {
        err && log(err)
        var count = rows[0]['count(*)'],
          learingRate = 1;
        while (count >= 1) {
          count /= 2;
          learingRate /= 2;
        }
        zoroDB.query('update url_word set p=p*? where url=?', [1 - learingRate, uw.urlId], (err, result) => {
          err && log(err)
          zoroDB.query('update url_word set p=p+? where url=? and word=?', [learingRate, uw.urlId, uw.wordId], (err, result) => {
            err && log(err)
            zoroDB.query('update url_word set p=? where p<? and url=?', [learingRate * learingRate, learingRate * learingRate, uw.urlId], (err, result) => {
              err && log(err)
              resolve()
            })
          })
        })
      })
    }),
    p2 = new Promise(resolve => {
      zoroDB.query('select count(*) from word', [], (err, rows, fields) => {
        err && log(err)
        var count = rows[0]['count(*)'],
          learingRate = 1;
        while (count >= 1) {
          count /= 2;
          learingRate /= 2;
        }
        zoroDB.query('update word set p=p*?', [1 - learingRate], (err, result) => {
          err && log(err)
          zoroDB.query('update word set p=p+? where id=?', [learingRate, uw.wordId], (err, result) => {
            err && log(err)
            resolve()
          })
        })
      })
    });
  Promise.all([p0, p1, p2]).then(() => {
    deal(uws.slice(1))
  })
}
